// auth
package middleware

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/config"
	dao2 "gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/dao"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

// TokenCheckCustomer token校验（用户侧）
func TokenCheckCustomer() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("X-TOKEN")
		if token == "" {
			global.Log.Error("无权限, X-TOKEN为空")
			c.JSON(http.StatusUnauthorized, model.Fail("无权限"))
			c.Abort()
		} else {
			payload, ok := util.ValidToken(token, config.Token().Key)
			if !ok {
				global.Log.Error("无权限, X-TOKEN无效")
				c.JSON(http.StatusUnauthorized, model.Fail("无权限"))
				c.Abort()
			}
			customer, err := dao2.QueryCustomerDetail("", payload.UserId)
			if err != nil || customer == nil {
				global.Log.Error("无权限, X-TOKEN无效, 未找到该用户", zap.Any("error", err))
				c.JSON(http.StatusUnauthorized, model.Fail("无权限"))
				c.Abort()
			}
			c.Set("USER", customer)
			c.Next()
		}
	}
}

// TokenCheckOperator token校验（管理侧）
func TokenCheckOperator() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("X-TOKEN")
		if token == "" {
			global.Log.Error("无权限, X-TOKEN为空")
			c.JSON(http.StatusUnauthorized, model.Fail("无权限"))
			c.Abort()
		} else {
			payload, ok := util.ValidToken(token, config.Token().Key)
			if !ok {
				global.Log.Error("无权限, X-TOKEN无效")
				c.JSON(http.StatusUnauthorized, model.Fail("无权限"))
				c.Abort()
			}
			operator, err := dao2.QueryOperatorDetail("", payload.UserId)
			if err != nil || operator == nil {
				global.Log.Error("无权限, X-TOKEN无效, 未找到该用户", zap.Any("error", err))
				c.JSON(http.StatusUnauthorized, model.Fail("无权限"))
				c.Abort()
			}
			c.Set("USER", operator)
			c.Next()
		}
	}
}
